#!/usr/bin/env bash
# bash <(curl -sLk https://gitee.com/uon/script/raw/master/shell/iperf3.sh)

function get_sys() {
    if grep -Eqi "CentOS" /etc/issue || grep -Eq "CentOS" /etc/*-release; then
        DISTRO='CentOS'
    elif grep -Eqi "Red Hat Enterprise Linux Server" /etc/issue || grep -Eq "Red Hat Enterprise Linux Server" /etc/*-release; then
        DISTRO='RHEL'
    elif grep -Eqi "Aliyun" /etc/issue || grep -Eq "Aliyun" /etc/*-release; then
        DISTRO='Aliyun'
    elif grep -Eqi "Fedora" /etc/issue || grep -Eq "Fedora" /etc/*-release; then
        DISTRO='Fedora'
    elif grep -Eqi "Debian" /etc/issue || grep -Eq "Debian" /etc/*-release; then
        DISTRO='Debian'
    elif grep -Eqi "Ubuntu" /etc/issue || grep -Eq "Ubuntu" /etc/*-release; then
        DISTRO='Ubuntu'
    elif grep -Eqi "Raspbian" /etc/issue || grep -Eq "Raspbian" /etc/*-release; then
        DISTRO='Raspbian'
    elif (uname -a | grep -Eqi synology)
        then
        DISTRO='Synology'
    else
        DISTRO='1'
    fi
    ###返回值
    echo ${DISTRO}
}


var_dir="/tmp/a3ff9b51-d73f-8b75-a27d-be3e2a66a360"
log_dir="/var/log/iperf3"

function install_ubuntu() {
    [ ! -d "${var_dir}" ] && mkdir -p "${var_dir}"
    [ ! -d "${log_dir}" ] && mkdir -p "${log_dir}"
    cd ${var_dir} || exit
    sudo apt remove -y iperf3 libiperf0
    sudo apt install -y libsctp1
    wget https://iperf.fr/download/ubuntu/libiperf0_3.9-1_amd64.deb
    wget https://iperf.fr/download/ubuntu/iperf3_3.9-1_amd64.deb
    sudo dpkg -i libiperf0_3.9-1_amd64.deb iperf3_3.9-1_amd64.deb
    rm -rf ${var_dir}

    systemctl stop iperf3 2>/dev/null
    systemctl disable iperf3 2>/dev/null

    cat >/usr/lib/systemd/system/iperf3.service <<EOF

[Unit]
Description=iperf3
After=network.target

[Service]
Restart=on-failure
RestartSec=1
Type=simple
StartLimitInterval=0
PIDFile=/run/iperf3.pid
ExecStart=iperf3 -s -i 1 --logfile ${log_dir}/iperf3.log
# ExecReload=/usr/sbin/nginx -g 'daemon on; master_process on;' -s reload
ExecStop=-/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/iperf3.pid
TimeoutStopSec=5
KillMode=mixed

[Install]
WantedBy=multi-user.target

EOF

    systemctl daemon-reload
    systemctl enable iperf3
    systemctl start iperf3
    systemctl status iperf3

}

function uninstall() {
    systemctl stop iperf3
    systemctl disable iperf3
    sudo apt remove -y iperf3 libiperf0
    rm -f "/usr/lib/systemd/system/iperf3.service"
    systemctl daemon-reload
    [ -d "${log_dir}" ] && rm -rf "${log_dir}"
}

if [ "$1" == "-u" ]; then
    uninstall
else

    if [ "$(get_sys)" == "Ubuntu" ]; then
        install_ubuntu
    else
        echo 暂不支持的系统
    fi
fi
